package org.jash.demo2205

import android.app.Application.ActivityLifecycleCallbacks
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import androidx.databinding.ObservableArrayMap
import androidx.databinding.ObservableMap
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.jash.demo2205.databinding.ActivityLoginBinding
import org.jash.demo2205.mvvm.BaseActivity
import org.jash.demo2205.utils.SPUtils
import org.jash.demo2205.utils.retrofit

@Route(path = "/shop/login")
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {
    val user:ObservableMap<String, String> by lazy { ObservableArrayMap() }
    val launcher:ActivityResultLauncher<Intent> by lazy { registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()) {
            val data = it.data
        if (data != null) {
            user["username"] = data.getStringExtra("username")
            user["password"] = data.getStringExtra("password")
        }
    } }

    override fun initData() {
        launcher
        viewModel.loginLiveData.observe(this) {
            SPUtils.instance.putString("token", it.token)
            SPUtils.instance.putString("user_info", Gson().toJson(it))
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
            ARouter.getInstance().build("/shop/shop").navigation()

        }
        binding.user = user
    }

    override fun initView() {
        binding.login.setOnClickListener {
            viewModel.login(user)
        }
        binding.gotoRegister.setOnClickListener {
            launcher.launch(Intent(this, RegisterActivity::class.java))
        }
    }

}